package com.wsx.ones.cloud.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangshuaixin on 17/5/13.
 */
public class GsonUtil {

    private static Gson gson;

    static {
        gson = new Gson();
    }

    public static synchronized Gson GetGson() {
        if (null == gson) {
            synchronized (GsonUtil.class) {
                if (null == gson)
                gson = new Gson();
            }
        }
        return gson;
    }


    public static String getString(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> List<T> toList(String json, Class<T> clz) {
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        List<T> list = new ArrayList<T>();
        for (final JsonElement ele : array) {
            list.add(gson.fromJson(ele, clz));
        }
        return list;
    }
}
